<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 设备详情 </span>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts" setup name="ViewsDeviceManagementInDeviceManagementList">
import { unref, defineProps, ref, onMounted, watch } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { inDeviceSenor } from '/@/api/device.management/inDeviceManagement'; // 假设这是请求接口的函数
import { useDrawer } from '/@/components/Drawer';
import { FormProps } from '/@/components/Form';

const props = defineProps<{
  tid: string | null
  hostId: string | null
  equipmentCode: string | null
}>();
// console.log('props', props.tid);

const { t } = useI18n('device.management.inDeviceManagement');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);

const getTitle = {
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: meta.title || t('设备管理表管理'),
};

const tableColumns: BasicColumn[] = [
  {
    title: t('设备名称'),
    dataIndex: 'fireHostId',
    key: 'a.fire_host_id',
    width: 80,
    align: 'left',
    slot: 'firstColumn',
  },
  {
    title: t('上报时间'),
    dataIndex:'reportTime',
    key: 'a.report_time',
    width: 80,
    align: 'left',
    customRender: ({ record }) => {
      const reportTime = record.reportTime;
      if (reportTime) {
        const date = new Date(reportTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      return '';
    },
  },
  {
    title: t('设备状态'),
    dataIndex:'sensorStatus',
    key: 'a.sensor_status',
    width: 80,
    align: 'left',
  },
  {
    title: t('上报内容'),
    dataIndex: 'content',
    width: 130,
    align: 'left',
  },
];

// 定义当前页码的响应式变量
const currentPage = ref(1);
// 定义每页显示数量的响应式变量
const pageSize = ref(10);
// 定义总记录数的响应式变量
const totalRecords = ref(0);

const [registerTable, { reload }] = useTable({
  api: async (params) => {
    try {
      if (props.tid === null|| props.tid === undefined) {
        return {
          count: 0,
          list: [],
          pageNo: 1,
          pageSize: 10
        };
      }
      const res = await inDeviceSenor(params);
      console.log('接口返回数据:', res);
      // 适配新的数据结构
      console.log('总记录数:', res.data.total);
      console.log('总页数:', res.data.pages);
      return {
        count: res.data.total,
        list: res.data.records,
        pageNo: res.data.current,
        pageSize: res.data.size,
      };
    } catch (error) {
      console.error('接口调用出错:', error);
      throw error;
    }
  },
  beforeFetch: (params) => {
    if (props.tid === null) {
      return null;
    }
    // 构造符合接口要求的请求负载
    params = {
      data: {
        enterpriseId: '',
        buildId: '',
        regionId: '',
        fireHostId: props.hostId,
        sensorId: props.equipmentCode,
        sensorStatus: '',
        content: '',
        reportTime: '',
        addTime: ''
      },
      page: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      },
      pageNo: currentPage.value,
      pageSize: pageSize.value
    };
    return params;
  },
  columns: tableColumns,
  canResize: true,
  pagination: {
    show: true,
    pageSize: pageSize.value,
    total: totalRecords.value,
    current: currentPage.value, // 注意这里是current，不是pageNo
    onChange: (page) => {
      currentPage.value = page;
      reload();
    },
    onShowSizeChange: (current, size) => {
      pageSize.value = size;
      reload();
    }
  }
});

function handleSuccess(record: Recordable) {
  reload({ record });
}

// 定义一个响应式变量来存储tid
const tidValue = ref(props.tid);
// 监听props.tid的变化
watch(() => props.tid, (newValue) => {
  tidValue.value = newValue;
  console.log('tid变化了，新值为:', newValue);
  if (newValue!== null) {
    reload();
  }
});

onMounted(() => {
  console.log('组件挂载时tid的值为:', tidValue.value);
  if (tidValue.value!== null) {
    reload();
  }
});
</script>